package com.example.blog.admin.service;


import com.example.blog.admin.pojo.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
@Slf4j
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username:{}", username);
        // 当用户登录的时候，springsecurity会将请求转发到此
        // 用户不存在，抛出异常， 存在，将用户名，密码，授权列表组装乘 springsecurity 的 user 对象并返回
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        UserDetails userDetails = new User(username, admin.getPassword(), new ArrayList<GrantedAuthority>());
        return userDetails;
    }
}
